package com.example.myapplicationktkt2.activity

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.example.myapplicationktkt2.R
import com.example.myapplicationktkt2.model.UserViewModel

class UserActivity : AppCompatActivity() {
    
    private lateinit var userViewModel: UserViewModel
    private lateinit var nameEditText: EditText
    private lateinit var ageEditText: EditText
    private lateinit var updateButton: Button
    private lateinit var nameTextView: TextView
    private lateinit var ageTextView: TextView
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user)
        
        // 初始化视图
        initViews()
        
        // 获取 ViewModel 实例
        userViewModel = ViewModelProvider(this)[UserViewModel::class.java]
        
        // 观察 LiveData 数据变化
        observeData()
        
        // 设置点击事件
        setupClickListeners()
    }
    
    private fun initViews() {
        nameEditText = findViewById(R.id.et_user_name)
        ageEditText = findViewById(R.id.et_user_age)
        updateButton = findViewById(R.id.btn_update)
        nameTextView = findViewById(R.id.tv_user_name)
        ageTextView = findViewById(R.id.tv_user_age)
    }
    
    private fun observeData() {
        // 观察用户名变化
        userViewModel.userName.observe(this) { name ->
            nameTextView.text = "用户名: $name"
        }
        
        // 观察用户年龄变化
        userViewModel.userAge.observe(this) { age ->
            ageTextView.text = "年龄: $age"
        }
    }
    
    private fun setupClickListeners() {
        updateButton.setOnClickListener {
            val name = nameEditText.text.toString()
            val age = ageEditText.text.toString().toIntOrNull() ?: 0
            
            // 更新数据
            userViewModel.updateUserName(name)
            userViewModel.updateUserAge(age)
        }
    }
}